package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.ChargeUnitAttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.util.JsonUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * @Classname ChargeUnitAttrLinkHandler
 * @Description 收费单位
 * @Author zhang.song
 * @Date 2022-02-07 11:32
 */
@Service
@AttrHandler(ChargeUnitAttrHandler.class)
public class ChargeUnitAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {

    @Autowired
    private OperateInstAttrService operateInstAttrService;

    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        String value = attr.getValue();
        if (KiteStringUtils.isEmpty(value) || !KiteStringUtils.isJsonObject(value)) {
            return;
        }

        Map<String, Object> dataMap = null;
        try {
            dataMap = JsonUtil.json2Object(value, Map.class);
        } catch (BaseAppException e) {
        }
        if(dataMap == null || dataMap.size() == 0) {
            return;
        }

        // 收费省、收费地市赋值
        KiteAttr chargeProvAttr = inst.getAttr("210008007");
        KiteAttr chargeCityAttr = inst.getAttr("210008008");
        if (Objects.nonNull(chargeProvAttr)) {
            String chargeProv = MapUtils.getString(dataMap, "chargeProv");
            operateInstAttrService.setAttrValue(inst, "210008007", chargeProv, data.getSceneInstId(), null);
        }
        if (Objects.nonNull(chargeCityAttr)) {
            String chargeCity = MapUtils.getString(dataMap, "chargeCity");
            operateInstAttrService.setAttrValue(inst, "210008008", chargeCity, data.getSceneInstId(), null);
        }

        String chargeUnitCode = MapUtils.getString(dataMap, "chargeUnitCode");
        String chargeUnitName = MapUtils.getString(dataMap, "chargeUnitName");
        attr.setValue(chargeUnitCode);
        attr.setValueDesc(chargeUnitName);
        operateInstAttrService.setAttrValue(inst, attr.getFieldName(), chargeUnitCode, data.getSceneInstId(), null);
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }
}
